package time_task

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//系统帐号流水方面的

//每天晚上23:55把系统帐号system_user里的day_cost置为0
func ClearSystemUserDayCost() error {
	sql := fmt.Sprintf("UPDATE %v SET day_cost = 0", TableSystemUser)
	o := NewDBOrm(DBChessCenter)
	_, err := o.Raw(sql).Exec()
	return err
}

//每周星期日晚上23:55把系统帐号system_user里的week_cost置为0
func ClearSystemUserWeekCost() error {
	sql := fmt.Sprintf("UPDATE %v SET week_cost = 0", TableSystemUser)
	o := NewDBOrm(DBChessCenter)
	_, err := o.Raw(sql).Exec()
	return err
}

//每月第一天凌晨00:03把系统帐号system_user里的week_cost置为0
func ClearSystemUserMonthCost() error {
	sql := fmt.Sprintf("UPDATE %v SET month_cost = 0", TableSystemUser)
	o := NewDBOrm(DBChessCenter)
	_, err := o.Raw(sql).Exec()
	return err
}

func StatSystemUser(r map[int64]int64) error {
	LogPc.Info("----------------------进入统计系统帐号流水---------------------------")
	ForExecute(listAllDaySystemUser, RecordDaySystemUser, r[RecordDaySystemUser])
	LogPc.Info("----------------------退出统计系统帐号流水---------------------------")
	return nil
}

func listAllDaySystemUser(t int64) error {
	var count int64
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
	`, TableSystemUser)
	o := NewDBOrm(DBChessCenter)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //没有系统帐号，统计毛线
		LogPc.Info("暂时没有系统帐号可以统计")
		return nil
	}
	sql := fmt.Sprintf(`
		SELECT
			uid
		FROM
			%v
		LIMIT ?,?
	`, TableSystemUser)
	var i, index, size int64
	size = 10 //每次取10个
	for index = 1; i < count; index++ {
		var uid []int64
		limit := (index - 1) * size
		n, err := o.Raw(sql, limit, size).QueryRows(&uid)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = statDaySystemUser(t, uid)
		if err != nil {
			return err
		}
	}

	return nil
}

type statSysUser struct {
	Diamond     int64 `json:"diamond"`
	OperateType int64 `json:"operate_type"`
}

func statDaySystemUser(t int64, uids []int64) error {
	var (
		startTime, endTime = StartEndTimeByTimestamp(t)
		//table              = GetMonthTableByTimestamp(TableSystemUserTran, t)
		table     = TableSystemUserTran
		thisMonth = ThisMonthByTimestamp(t) //当前时间戳的所在月201803
	)
	sql := fmt.Sprintf(`
		SELECT
			IF(SUM(diamond) is NULL,0,SUM(diamond)) AS diamond,operate_type
		FROM
			%v
		WHERE
			sys_uid = ? AND create_time > %v AND create_time < %v
		GROUP BY
			operate_type
	`, table, startTime, endTime)

	o := NewDBOrm(DBChessLog)
	for _, uid := range uids {
		var ss []statSysUser
		o.Raw(sql, uid).QueryRows(&ss)
		for _, v := range ss {
			data := map[string]interface{}{
				"sys_uid":      uid,
				"diamond":      v.Diamond,
				"operate_type": v.OperateType,
				"create_time":  endTime - 1,
			}
			NewOrUpdateChessLog(data, TableDaySystemUser, o)
			n, err := UpdateAddMonthSystemUser(uid, v.OperateType, v.Diamond, thisMonth, o)
			if err != nil {
				LogPc.Error(fmt.Sprintf("统计系统帐号流水月报表时失败:%v", err))
			}
			if n == 0 { //说明当月第一次统计,要新建一个
				data["create_time"] = thisMonth
				NewOrUpdateChessLog(data, TableMonthSystemUser, o)
			}
		}
	}

	return nil
}

func UpdateAddMonthSystemUser(sysUid, operateType, diamond int64, createTime string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	condition := fmt.Sprintf(`sys_uid = %v AND operate_type = %v AND create_time = %v`,
		sysUid, operateType, createTime)
	sql := fmt.Sprintf(`UPDATE %v SET diamond = diamond + %v WHERE %v`, TableMonthSystemUser, diamond, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()

}
